Page({
    data: {
      wifiList: [],
      ssid: '',
      password: '',
      socketOpen: false,
      socketMsgQueue: []
    },
  
    onLoad: function() {
      this.startWifi();
    },
  
    startWifi: function() {
      wx.startWifi({
        success: res => {
          console.log('startWifi success', res);
          this.getWifiList();
        },
        fail: err => {
          console.log('startWifi fail', err);
        }
      });
    },
  
    getWifiList: function() {
      wx.getWifiList({
        success: res => {
          console.log('getWifiList success', res);
          wx.onGetWifiList(res => {
            this.setData({
              wifiList: res.wifiList
            });
          });
        },
        fail: err => {
          console.log('getWifiList fail', err);
        }
      });
    },
  
    bindInputSSID: function(e) {
      this.setData({
        ssid: e.detail.value
      });
    },
  
    bindInputPassword: function(e) {
      this.setData({
        password: e.detail.value
      });
    },
  
    connectToWifi: function() {
      const { ssid, password } = this.data;
      wx.connectWifi({
        SSID: ssid,
        password: password,
        success: res => {
          console.log('connectWifi success', res);
          wx.showToast({
            title: 'Wi-Fi 连接成功',
            icon: 'success'
          });
          // 连接到 WebSocket 服务器
          this.connectToWebSocket();
        },
        fail: err => {
          console.log('connectWifi fail', err);
          wx.showToast({
            title: 'Wi-Fi 连接失败',
            icon: 'none'
          });
        }
      });
    },
  
    connectToWebSocket: function() {
      const url = 'ws://your-robot-ip:port'; // 替换为你机器人的 WebSocket 服务器地址
      wx.connectSocket({
        url: url,
        success: res => {
          console.log('connectSocket success', res);
        },
        fail: err => {
          console.log('connectSocket fail', err);
        }
      });
  
      wx.onSocketOpen(() => {
        console.log('WebSocket 已连接');
        this.setData({
          socketOpen: true
        });
        this.sendSocketMessage('Hello, Robot!');
      });
  
      wx.onSocketMessage((res) => {
        console.log('收到服务器内容：' + res.data);
        // 处理服务器发送来的消息
      });
  
      wx.onSocketClose(() => {
        console.log('WebSocket 已关闭');
        this.setData({
          socketOpen: false
        });
      });
  
      wx.onSocketError((err) => {
        console.error('WebSocket 错误：', err);
      });
    },
  
    sendSocketMessage: function(msg) {
      if (this.data.socketOpen) {
        wx.sendSocketMessage({
          data: msg
        });
      } else {
        this.data.socketMsgQueue.push(msg);
      }
    }
  });